package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    WemediaFeign wemediaFeign;

    @Autowired
    GreeTextScan greeTextScan;

    @Autowired
    GreenImageScan greenImageScan;

    @Value("${file.oss.web-site}")
    private String webSite;

    /**
     * 自媒体文章审核
     *
     * @param wmNewsId
     */
    @Override
    public void autoScanByMediaNewsId(Integer wmNewsId) {
        //id检查
        if (wmNewsId == null) {
            log.error("当前的审核id空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取当前ID文章信息
        WmNews wmNews = wemediaFeign.findById(wmNewsId);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            log.error("审核的自媒体文章不存在，自媒体的id:{}", wmNewsId);
            return;
        }
        //判断文章状态
        //文章状态为4，说明人工审核通过，直接保存文章
        if (wmNews.getStatus().equals(WmNews.Status.ADMIN_SUCCESS.getCode())
                && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            //保存
            saveAppArticle(wmNews);
            return;
        }
        //文章状态为8，说明审核通过，但是发布时间小于等于当前时间 ，直接保存文章
        if (wmNews.getStatus().equals(WmNews.Status.SUCCESS.getCode())
                && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            //保存
            saveAppArticle(wmNews);
            return;
        }
        //文章状态为1，待审核
        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            // 抽取文章内容中的文本和图片
            //4.1 自管理敏感词审核
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            //4.2 阿里云审核文本内容
            boolean isTextScan=handleTextScan(
                    (String)contentAndImagesResult.get("content"),wmNews
            );
            if (!isTextScan)return;
            //4.3 阿里云图片审核
            boolean isImageScan=handleImagesScan(
                    (List) contentAndImagesResult.get("images"), wmNews
            );
            if (!isImageScan)return;

            //4.4 判断文章发布时间大于当前时间，修改状态8
            if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(),"文章审核通过，待发布");
            }

            //5 保存文章相关数据
            saveAppArticle(wmNews);

            //6 TODO 同步索引库

        }

    }

    private boolean handleImagesScan(List images, WmNews wmNews) {
        //无图则不需要审核直接返回
        if (images==null||images.size()==0){
            return true;
        }
        boolean flag=true;


        try {                //去重
            images.stream().distinct().collect(Collectors.toList());
            Map map = greenImageScan.imageUrlScan(images);
            if (map.get("suggestion").equals("block")){
                flag=false;
                updateWmNews(wmNews,(short)2,
                        "阿里云审核--文章内容包含违规内容");
            }
            if (map.get("suggestion").equals("review")){
                flag=false;
                updateWmNews(wmNews,(short)3,
                        "需要人工审核 ");
            }
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
            updateWmNews(wmNews, (short) 3, "阿里云审核失败，转入人工审核");
            flag = false;
        }
        return flag;
    }

    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag=true;
        try {
            Map map = greeTextScan.greeTextScan(content);
            if (map.get("suggestion").equals("block")){
                flag=false;
                updateWmNews(wmNews,(short)2,
                        "阿里云审核--文章内容包含违规内容");
            }
            if (map.get("suggestion").equals("review")){
                flag=false;
                updateWmNews(wmNews,(short)3,
                        "需要人工审核 ");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(" aliyun handleTextScan error:{} ",e);
            flag = false;
            updateWmNews(wmNews, (short)3,
                    "阿里云审核失败，转人工审核");
        }


        return false;
    }

    @Autowired
    AdSensitiveMapper adSensitiveMapper;

    //敏感词审核
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        //查询所有敏感词
        List<String> sensitiveList = adSensitiveMapper.findAllSensitive();
        //初始化DFA搜索
        SensitiveWordUtil.initMap(sensitiveList);
        //匹配敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            flag = false;
            updateWmNews(wmNews, (short) 2, "文章中包含敏感词：" + map);
        }
        return flag;
    }

    //修改文章
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.WMNEWS_UPDATE_ERROR);
        }
    }



    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String content = wmNews.getContent();
        if (StringUtils.isNotBlank(content) && content.length() < 10000) {
            List<Map> contentList = JSON.parseArray(content, Map.class);
            // 文本
            StringBuilder sb = new StringBuilder();
            // 文章标题
            sb.append(wmNews.getTitle()).append("__hmtt__");
            // 图片列表
            List<String> images = new ArrayList<>();
            for (Map<String, String> map : contentList) {
                // 文本
                if (map.get("type").equals("text")) {
                    // fhasfsa 破冰
                    // 毒素dgfasjhfas
                    // 冰毒
                    sb.append(map.get("value"));
                    // 处理拼接出现敏感词问题
                    sb.append("__hmtt__");
                }
                // 图片（有前缀）
                if (map.get("type").equals("image")) {
                    images.add(map.get("value"));
                }
            }
            // 解析 封面图片
            String wmNewsImages = wmNews.getImages();
            if (StringUtils.isNotBlank(wmNewsImages)) {
                String[] split = wmNewsImages.split(",");
                for (String url : split) {
                    images.add(webSite + url);
                }
            }


            // 返回结果
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("content", sb.toString());
            resultMap.put("images", images);

            return resultMap;
        }


        return null;
    }
    @Autowired
    AdChannelMapper adChannelMapper;
    @Autowired
    ArticleFeign articleFeign;

    //保存文章
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        //文章存在 saveArticle 执行修改操作
        if (wmNews.getArticleId()!=null){
            articleDto.setId(wmNews.getArticleId());
        }
        //设置作者信息
        WmUser wmUser = wemediaFeign.findWmUserById(wmNews.getId());
        if (wmUser==null){
            articleDto.setAuthorName(wmUser.getName());
        }
        //设置频道数据
        AdChannel channel = adChannelMapper.selectById(wmNews.getChannelId());
        if (channel==null){
            articleDto.setChannelId(channel.getId());
            articleDto.setChannelName(channel.getName());
        }
        //文章布局
        articleDto.setLayout(wmNews.getType().intValue());
        articleDto.setFlag((byte) 0);
        articleDto.setCreatedTime(new Date());
        articleDto.setOrigin(true);
        //返回文章articleDto
        return articleFeign.saveArticle(articleDto);

    }

}
